package com.uum.mq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.uum.mq.pojo.entity.SysMqMsg;
import com.uum.mq.pojo.entity.SysUserMsg;
import com.uum.mq.mapper.SysUserMsgMapper;
import com.uum.mq.service.SysMqMsgService;
import com.uum.mq.service.SysUserMsgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uum.web.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserMsgServiceImpl extends ServiceImpl<SysUserMsgMapper, SysUserMsg> implements SysUserMsgService {

    private final SysMqMsgService sysMqMsgService;

    @Override
    public List<SysMqMsg> unreadMsg() {
        //查询所有消息
        List<SysMqMsg> allMsg = sysMqMsgService.list();
        //查询用户已读消息
        List<Long> msgIdList = baseMapper.selectList(new LambdaQueryWrapper<SysUserMsg>().eq(SysUserMsg::getUserId, JwtUtils.getUserId()).select(SysUserMsg::getMessageId))
                .stream().map(SysUserMsg::getMessageId).collect(Collectors.toList());
        //未查询出已读消息，则返回所有消息
        if (msgIdList.isEmpty()) {
            return allMsg;
        }
        //返回未读消息
        List<SysMqMsg> unreadList = allMsg.stream().filter(item -> !msgIdList.contains(item.getId())).collect(Collectors.toList());
        return unreadList;
    }

    @Override
    public List<Long> readAll(Long userId) {
        //1.先删除该用户下所有已读消息
        baseMapper.delete(new LambdaQueryWrapper<SysUserMsg>().eq(SysUserMsg::getUserId, userId));
        //2.查出所有消息
        List<Long> allMsg = sysMqMsgService.list(new LambdaQueryWrapper<SysMqMsg>().select(SysMqMsg::getId)).stream().map(SysMqMsg::getId).collect(Collectors.toList());
        return allMsg;
    }
}
